
package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import bean.Employee;
import bean.Model;
import bean.User;
import bean.UserType;
import dao.EmployeeDAO;
import dao.UserDAO;
import formBean.EmployeeAc;

public class CreateEmployeeAccAction extends Action {
	private FormBeanFactory<EmployeeAc> formBeanFactory = FormBeanFactory.getInstance(EmployeeAc.class);
	
	private EmployeeDAO employeeDAO = null;
	private UserDAO userDAO = null;
	
	public CreateEmployeeAccAction(Model model) {
		this.employeeDAO = model.getEmployeeDAO();
		this.userDAO = model.getUserDAO();
	}
	
	@Override
	public String getName() {
		return "createEmployee.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		
		try {
			EmployeeAc form = formBeanFactory.create(request);
			request.setAttribute("form", form);
			
			if (!form.isPresent()) {
				return "employeeAc.jsp";
			}
			
			errors.addAll(form.getValidationErrors());
			
			if (errors.size() > 0) {
				return "employeeAc.jsp";
			}
			
			User user = userDAO.lookUpByUsername(form.getUserName());
			if (user != null ){
				errors.add("The username already exists.");
				return "employeeAc.jsp";
			}
			
			Employee e= new Employee();
			e.setFirstname(form.getFirstName());
			e.setLastname(form.getLastName());
			e.setUsername(form.getUserName());
			e.setPassword(form.getPassword());
			
			errors.addAll(employeeDAO.createEmployee(e));
			
			if (errors.size() > 0) {
				return "employeeAc.jsp";
			}
					
			e = employeeDAO.lookUpByUsername(form.getUserName());
			User newUser = new User();
			newUser.setCustomer(false);
			newUser.setUserId(e.getId());
			newUser.setUsername(form.getUserName());
			
			errors.addAll(userDAO.create(newUser));
			
			if (errors.size() > 0) return "employeeAc.jsp";
			
			request.setAttribute("message", "You have created the employee " + e.getUsername() + ".");	
			return "employeeConsole.jsp";
		} catch (FormBeanException e) {
			e.printStackTrace();
			errors.add(e.getMessage());
			return "employeeAc.jsp";
		}		
	}

	@Override
	public UserType getType() {
		return UserType.Employee;
	}

}
